'use strict'
const express = require('express')
const path = require('path')
var ejs = require('ejs');
var bodyParser = require('body-parser');
var request = require('request');
var http = require('http');
var url = require('url');
const app = express()

// var urlencodedParser = bodyParser.urlencoded({ extended: false })
var urlencodedParser = bodyParser.json()

app.use(express.static(path.join(__dirname, 'views')))
app.set('views', './views');
app.engine('html', ejs.__express);
app.set('view engine', 'html');
app.use(express.static('views'))

app.get('/order', function(request, response) {
    response.render('order', {
        // title:'首页',
        // content:'Render template'
    });
});

app.post('/test', urlencodedParser, function(request, response) {
    var data = request.body
    console.log(data)
    response.send(data)
});


app.post('/submit_order', urlencodedParser, function(req, res) {

    var url = "https://www.baidu.com"
    var uid = req.cookies.name;
    var formData = {
        name: req.body.name,
        address: req.body.address,
        address_detail: req.body.address_detail,
        uid: uid,
        phone: req.body.phone,
    };

    request({
        url: url,
        method: "POST",
        json: true,
        headers: { "content-type": "application/json" },
        formData: formData
    }, function(error, response, body) {
        //console.log(response);
        if (!error && response.statusCode == 200) {

            res.json({ state: true });

        } else {
            console.log('fail');
            res.json({ state: false });
        }

    });

});

app.post('/get_ans', urlencodedParser, function(req, res) {
    var formData = {
        uid: req.cookies.name,
    };

    request({
        url: "https://www.baidu.com",
        method: "POST",
        json: true,
        headers: { "content-type": "application/json" },
        formData: formData
    }, function(error, response, body) {
        console.log("response.headers");
        console.log(response.headers);
        if (!error && response.statusCode == 200) {
            res.headers = response.headers
            res.json({ msg: response.body.msg, state: response.body.state });

        } else {
            console.log('fail');
            res.json({ state: false });
        }
    });
});


app.listen(8080, () => {
    console.log(`App listening at port 8080`)
})